<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree title="菜单列表" treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" ref="treeRef" checkable search
      checkStrictly :clickRowToExpand="false" :treeData="treeData" :fieldNames="{ key: 'id', title: 'title' }"
      @select="handleSelect" @check="handleCheck" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, unref, watch } from 'vue';
import { BasicTree, TreeActionType } from '/@/components/Tree';
import { getViewTree } from '/@/api/system/view';

onMounted(async () => {
  await fetch();
  getTree().expandAll(true);
})

watch(() => props.modelValue, (record) => {
  if (record) {
    fetch()
    emit('update:modelValue', false)
  }
})

const props = defineProps<{ modelValue: boolean }>();
const emit = defineEmits(['select', 'check', 'update:modelValue'])
const treeData = ref<any[]>([]);
const treeRef = ref<Nullable<TreeActionType>>(null);

function getTree() {
  const tree = unref(treeRef);
  if (!tree) {
    throw new Error('tree is null!');
  }
  return tree;
}

async function fetch() {
  treeData.value = (await getViewTree()) as any;
}

function handleSelect(keys: any) {
  const item = getTree().getSelectedNode(keys[0]);
  emit('select', item);
}
function handleCheck(keys: any) {
  emit('check', keys.checked);
}
</script>
